package com.zgw.fireline.base;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

import com.zgw.fireline.base.dialogs.WidgetInfoDialog;

public class DbugContext {

	public static void RunDebug(Runnable runable) {
		Listener listener = createDebugListener();
		Display.getDefault().addFilter(SWT.Paint, listener);
		Display.getDefault().addFilter(SWT.MouseEnter, listener);
		Display.getDefault().addFilter(SWT.MouseDown, listener);
		try {
			runable.run();
		} finally {
			Display.getDefault().removeFilter(SWT.Paint, listener);
			Display.getDefault().removeFilter(SWT.MouseEnter, listener);
			Display.getDefault().removeFilter(SWT.MouseDown, listener);
		}
	}

	private static Listener createDebugListener() {
		Listener debugListener = new Listener() {
			Control widget = null;

			public void handleEvent(Event event) {
				if (!(event.widget instanceof Control))
					return;

				if (event.type == SWT.MouseEnter) {
					if (widget != null && !widget.isDisposed())
						widget.redraw();
					widget = getIDesignWidget((Control) event.widget);
					if (widget != null && !widget.isDisposed())
						widget.redraw();
				} else if (event.type == SWT.Paint && widget == event.widget) {
					GC gc = new GC(widget);
					gc.setForeground(event.display
							.getSystemColor(SWT.COLOR_RED));
					gc.drawRectangle(0, 0, event.width - 1, event.height - 1);
					gc.dispose();
				} else if (event.type == SWT.MouseDown
						&& widget == event.widget) {
					WidgetInfoDialog dlg = new WidgetInfoDialog(new Shell(),
							SWT.NONE);
					dlg.open();
					dlg.setWidget((IDesignOnLine) widget);
				}
			}
		};
		return debugListener;
	}

	private static Control getIDesignWidget(Control control) {
		while (control != null && !control.isDisposed()) {
			for (Class c : control.getClass().getInterfaces()) {
				if (c == IDesignOnLine.class) {
					return control;
				}
			}
			if (control instanceof Shell) {
				break;
			}
			control = control.getParent();
		}
		return null;
	}

}
